<template>
	<div class="evidence-unit-evidenceIn-container">
		<el-card shadow="hover" body-style="padding:8px; ">
			<el-row justify="end" style="margin-bottom: 15px; margin-top: 3px">
				<el-col :span="24">
					<div style="float: left; height: 40px; width: 5px; background: green"></div>
					<div style="float: left; margin-top: 10px; margin-left: 20px; font-size: 16px">出库清单</div>
				</el-col>
			</el-row>
			<el-table
				ref="multipleTable"
				:data="tableData"
				:default-sort="{ prop: 'name', order: 'descending' }"
				 :row-style="{ height: '37px' }"
				:cell-style="{ padding: '0' }"
				size="medium"
				style="width: 100%"
			>
				<el-table-column align="center" label="序号" type="index" width="60"> </el-table-column>
				<el-table-column align="center" property="no" sortable label="物品编号" show-overflow-tooltip />
				<el-table-column align="center" sortable label="物品名称/数量" show-overflow-tooltip>
					<template #default="scope">{{ `${scope.row.name}/${scope.row.quantity}` }}</template>
				</el-table-column>
				<el-table-column align="center" property="source" sortable label="规格型号" show-overflow-tooltip />
				<el-table-column align="center" property="extractionParts" sortable label="产地" show-overflow-tooltip />
				<el-table-column align="center" property="evidencePerson" sortable label="颜色/获取时间" show-overflow-tooltip>
					<template #default="scope">{{ `${scope.row.extractionPersonName}/${dateFormat(scope.row.extractionDateTime)}` }}</template>
				</el-table-column>
				<el-table-column align="center" property="extractMethod" sortable label="获取方式" show-overflow-tooltip />
				<el-table-column align="center" property="status" sortable label=" 物品状态" show-overflow-tooltip>
					<template #default="scope">{{ `${getEvidenceStatus(scope.row.status) ?? '未知'}` }}</template>
				</el-table-column>
				<el-table-column align="center" property="location" sortable label="位置" show-overflow-tooltip />
				<el-table-column align="center" label="操作" width="150px">
					<template #default="scope">
						<el-button type="primary" @click="onDelete(scope.row)" plain size="mini">移除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-row justify="end" style="margin-bottom: 15px; margin-top: 10px">
				<el-col :span="24">
					<div style="float: left; height: 40px; width: 5px; background: green"></div>
					<div style="float: left; margin-top: 10px; margin-left: 20px; font-size: 16px">出库交接信息</div>
				</el-col>
			</el-row>
		    <el-form ref="refForm" :rules="rules" :model="formInline" :inline="true" size="mini" label-width="100px">
				<el-row >
					<el-form-item label="接收单位" prop="transferorOrgan">
						<el-input v-model="formInline.transferorOrgan" placeholder="请读取"></el-input>
						<!-- <el-select filterable allow-create v-model="formInline.transferorOrgan" placeholder="请选择...">
							<el-option v-for="item in options.tqdws" :key="item.value" :label="item.label" :value="item.value"> </el-option>
						</el-select> -->
					</el-form-item>
					<el-form-item label="接收人"  prop="transferor">
						<el-input v-model="formInline.transferor" placeholder="请读取"></el-input>
						<!-- <el-select filterable allow-create v-model="formInline.transferor" placeholder="请选择...">
							<el-option v-for="item in options.tqrs" :key="item.value" :label="item.label" :value="item.value"> </el-option>
						</el-select> -->
					</el-form-item>
					<el-form-item label="接收电话"  prop="transferorPhone">
						<el-input v-model="formInline.transferorPhone" placeholder="请读取"></el-input>
					</el-form-item>
					<el-form-item label="出库原因"  prop="deliveryDicType">
						<el-select filterable allow-create v-model="formInline.deliveryDicType" placeholder="请选择...">
							<el-option v-for="item in options.ckyys" :key="item.value" :label="item.label" :value="item.value"> </el-option>
						</el-select>
					</el-form-item>
				</el-row>
				<el-row>
					<el-form-item label="备注"   style="width: 100%; margin-top: 0px">
						<el-input v-model="formInline.remark" type="textarea" placeholder="请读取"></el-input>
					</el-form-item>
				</el-row>
				<el-row>
					<el-form-item label="凭证上传" style="width: 100%; margin-top: 10px" show-message="">
						<el-upload
							:action="UploadUrl"
							:headers="customsHeaders"
							:data="{
								ty: '3',
								id: '0',
							}"
							list-type="picture-card"
							:auto-upload="true"
							:on-success="onSuccess"
							:file-list="fileList"
							:before-remove="handleRemove"
							:on-preview="handlePictureCardPreview"
						>
							<template #default>
								<i class="el-icon-plus"></i>
							</template>
							<template #tip>
								<div
									class="el-upload el-upload--picture-card el-icon-camera"
									@click="onCameraInfo(1)"
									style="margin-left: 10px; font-size: 30px; color: #8c939d"
								></div>
								<div
									class="el-upload el-upload--picture-card  el-icon-user"
									@click="onCameraInfo(2)"
									style="margin-left: 10px; font-size: 30px; color: #8c939d;display: none;"
								></div>
							</template>
						</el-upload>
						<el-dialog v-model="dialogVisible">
							<el-image style="width: 800px; height: 600px" :src="dialogImageUrl" alt="" />
						</el-dialog>
					</el-form-item>
				</el-row>
				<el-row justify="center" style="margin-top: 20px">
					<el-button type="primary" icon="el-icon-check" @click="onDetailsInfo" align="center" size="medium">出 库</el-button>
				</el-row>
				<div style="color:red;display:none;">请对文书、报告、情况说明等凭证进行拍照或上传操作</div>
			</el-form>
		</el-card>
	</div>
</template>
<script lang="ts">
import { getCurrentInstance, reactive, toRefs, computed, nextTick,ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from '/@/store/index';
import { dateFormat, evidenceStatusName, initOrgansAndUers, getEvidenceStatus, getOutType, UploadUrl } from '/@/common';
import { queryImgs } from '/@/api/common';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Session } from '/@/utils/storage';
import { postEvidenceTransfere } from '/@/api/evidence/transfere';
import { openCamera,openCameraForPhoto } from '/@/api/hardware/index';

export default {
	methods: {},
	name: 'EvidenceIn',
	components: {},
	setup() {
		const { proxy } = getCurrentInstance() as any;
		const router = useRouter();
		const route = useRoute();
		const store = useStore();
		const state = reactive({
			isShowDialog: false,
			dialogVisible: false,
			fileList: [],
			dialogImageUrl: '',
			rules: {
				transferorOrgan: [
					{    
						required: false,
						message: '请输入接收单位',
						trigger: 'change',
					},
				],
				transferor: [
					{
						required: false,
						message: '请输入接收人',
						trigger: 'change',
					},
				],
				transferorPhone: [
					{
						required: false,
						message: '请输入接收电话',
						trigger: 'change',
					},
				],
				deliveryDicType: [
					{
						required: false,
						message: '请选择出库原因',
						trigger: 'change',
					},
				],
				
			},
			formInline: {
				transferorOrgan: '',
				transferor: '',
				transferorPhone: '',
				remark: '',
				deliveryDicType: '',
				signImg: '',
				saveSignImg: '',
				deliveryTime:'',
				imgs: [],
			},
			tableData: store.state.customs.customs.selectionEvidences,
			formInlineCase: store.state.customs.customs.formInlineCase,
			options: {
				tqrs: [],
				tqdws: [],
				ckyys: [],
			},
		});
		const handleRemove = async (file:any,fileList) => {

			await ElMessageBox.confirm('此操作将永久删除, 是否继续?', '提示', { confirmButtonText: '删除', cancelButtonText: '取消', type: 'warning' })
			.then(() => {
		var _urlPath='';
		if(file.response) _urlPath=file.response.data;
		else
		_urlPath=file.url;
		state.formInline.imgs.pop(_urlPath);
	})
	.catch(() => {
		throw new Error();
	});


			
		};
		const handlePictureCardPreview = (file) => {
			nextTick(() => {
				var _urlPath='';
					if(file.response) _urlPath=file.response.data;
					else
					_urlPath=file.url;
				state.dialogImageUrl = _urlPath;
				state.dialogVisible = true;
			});
		};

		const refForm = ref();
		const onDetailsInfo = async () => {
			// if (!state.formInline.deliveryDicType) {
			// 	ElMessage.warning('请选择出库原因');
			// 	return false;
			// }

			// if (!state.formInline.remark) {
			// 	ElMessage.warning('请填写备注');
			// 	return false;
			// }

			if(state.formInline.imgs.length==0)
				{
					//ElMessage.warning('请上传或者拍照');
					//return;
				}

			await refForm.value.validate((valid) => {
				if (valid) {

			const list = state.tableData.map((x) => {
				return {
					evidenceId: x.id,
					evidenceStatus: 2,
					approveStatus: 0,
					deliveryDicType: Number(state.formInline.deliveryDicType),
					deliveryDicTypeName: getOutType(Number(state.formInline.deliveryDicType)),
					EvidenceQuantity: x.quantity,
					receiver: state.formInline.transferor,
					receiverPhone: state.formInline.transferorPhone,
					receiverOrgan: state.formInline.transferorOrgan,
					remark: state.formInline.remark,
				};
			});
			 postEvidenceTransfere({
				imgs: state.formInline.imgs,
				list: list,
				status: 2,
			}).then((res: any) => {
				if (res.success) {
					ElMessage.success('出库成功');
					state.formInline.saveSignImg = res.data.signImg;
					state.formInline.imgs = [];
					if (res.data.signImg) {
						state.formInline.imgs = [{ url: res.data.signImg, type: 6 }];
					}
					if(res.data.deliveryTime)
					state.formInline.deliveryTime=res.data.deliveryTime;
					store.dispatch('customs/setCustoms', {
						selectionEvidences: state.tableData.map((x) => {
							x.status = 2;
							x.cabinetCode = res.data.cabinetCode;
							return x;
						}),
						transfereInfo: state.formInline,
						formInlineCase: state.formInlineCase,
						deliveryNo: res.data.deliveryNo,
						showinventory:true,
					});
					router.push({path:'/evidence/unit/outDetails', query:{ t : new Date().getTime() }});
					closeCurrentTagsView();
				}
					});
				}
			});
		};

		const closeCurrentTagsView = () => {
			proxy.mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
		};
		(function () {
			initOrgansAndUers(state.options, () => {
				nextTick(() => {
					const userInfo = Session.get('userInfo');
					state.formInline.transferorOrgan = userInfo.organName;
					state.formInline.transferor = userInfo.userName;
					state.formInline.transferorPhone = userInfo.phone;
				});
			});
		})();
		function onSuccess(response, file, fileList) {
			if (response.success) {
				state.formInline.imgs.push(response.data);
				ElMessage.success('上传成功');
			}
		}
		const customsHeaders = computed(() => {
			return {
				Authorization: `Bearer ${Session.get('token')}`,
			};
		});
		function onDelete(row) {
			const index = state.tableData.findIndex((x) => x.id === row.id);
			state.tableData.pop(index);
		}
		
		function addimgs(imgsUrl)
		{

			// imgsUrl='http://127.0.0.1:5055/img/202402282129704.jpg';
			if(state.formInline.imgs.length!=state.fileList.length)
			{
				//删除state.fileList
				state.fileList.splice(0,state.fileList.length);
				for(var i = 0;i<state.formInline.imgs.length;i++){
					var _name=state.formInline.imgs[i];
					state.fileList.push({name: _name, url: _name });
				}
			}
		   state.formInline.imgs.push(imgsUrl);			
		   state.fileList.push({name: imgsUrl, url: imgsUrl });
		}
	

		function onCameraInfo(ty) {
			var ticks = new Date().getTime(); 
			var _typeid = 3;
			var _data = { key: '', type: _typeid, relevanceNo: ticks, relevanceId:ticks,url: import.meta.env.VITE_API_URL + '/common/upload/base64img' };
			if(ty == "2"){
				openCameraForPhoto(_data).then(function(){
					queryImgs(ticks,_typeid).then(function(ret:any){
						if(ret.success){
							for(var i = 0;i<ret.data.length;i++){
								var _item = ret.data[i];
								addimgs(_item.url);
							}
						}
					});
				});
				return;
			}
			//ty:1.物品,2.头像
			store.dispatch('hardware/getHardwareConfigByKey', 'yjpz_gaopaiyi').then(function (cfg) {
				if (!cfg || !cfg.res1) {
					ElMessage('未配置【高拍仪配置】');
					return;
				}
				_data.key = cfg.res1;
				openCamera(_data).then(function(){
					queryImgs(ticks,_typeid).then(function(ret:any){
						if(ret.success){
							for(var i = 0;i<ret.data.length;i++){
								var _item = ret.data[i];
								addimgs(_item.url);
							}
						}
					});
				});
			});
		}
		return {
			refForm,
			handleRemove,
			handlePictureCardPreview,
			onDetailsInfo,
			closeCurrentTagsView,
			dateFormat,
			onCameraInfo,
			evidenceStatusName,
			onSuccess,
			customsHeaders,
			getEvidenceStatus,
			UploadUrl,
			onDelete,
			...toRefs(state),
		};
	},
};
</script>
